import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { loginAPI, getProfileAPI } from "@/apis/uesr";


const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState:{
        // 初始化的时候，本地如果有，取本地数据
        // token: localStorage.getItem('token_key') || ''
        token: getToken() || '',
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action){
            state.token = action.payload
            // 本地持久化存储 （下面一行封装了，统一管理）
            // localStorage.setItem('token_key', action.payload)
            _setToken(action.payload)
        },
        setUserInfo(state, action){
            state.userInfo = action.payload
        },
        // 退出登录时清除用户信息
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions
const userReducer = userStore.reducer


// 登录方法
const fetchLogin = (loginForm) => {
    return async(dispatch) => {
        // 发送异步请求
        // const res = await request.post('/authorizations', loginForm)
        const res = await loginAPI(loginForm)
        // 提交同步action进行token的存入
        dispatch(setToken(res.data.token))
    }
}

// 获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        // const res = await request.get('/user/profile')
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}



export { setToken, fetchLogin, fetchUserInfo, clearUserInfo }
export default userReducer
